# -*- coding: utf-8 -*-
"""
系统监控管理API

按照模块文档2.4节要求提供系统监控功能的API接口
"""

from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from datetime import datetime
import logging

from ....core.database import get_db
from ....auth.jwt_auth import get_current_active_user
from ....services.monitoring_service import MonitoringService
from ....services.log_service import LogService
from ....services.rbac_service import PermissionDecorator
from ....core.exceptions import ValidationError, BusinessError
from ....core.dto import ResponseDTO

logger = logging.getLogger(__name__)
router = APIRouter()


# ==================== 数据模型 ====================

class LogQueryRequest(BaseModel):
    """日志查询请求"""
    log_type: Optional[str] = Field(None, description="日志类型")
    level: Optional[str] = Field(None, description="日志级别")
    start_time: Optional[datetime] = Field(None, description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    user_id: Optional[int] = Field(None, description="用户ID")
    keyword: Optional[str] = Field(None, description="关键词")
    ip_address: Optional[str] = Field(None, description="IP地址")


class LogAnalysisRequest(BaseModel):
    """日志分析请求"""
    analysis_type: str = Field(..., description="分析类型: activity/error/security/performance")
    time_range: int = Field(24, description="时间范围(小时)")
    group_by: str = Field("hour", description="分组方式: hour/day/user/ip/operation")


class LogExportRequest(BaseModel):
    """日志导出请求"""
    export_format: str = Field("json", description="导出格式: json/csv")
    log_type: Optional[str] = Field(None, description="日志类型筛选")
    start_time: Optional[datetime] = Field(None, description="开始时间")
    end_time: Optional[datetime] = Field(None, description="结束时间")
    max_records: int = Field(10000, description="最大记录数")


# ==================== 系统状态监控API ====================

@router.get("/system/status", response_model=ResponseDTO[Dict], summary="获取系统状态")
@PermissionDecorator.require_permission("system.monitoring", "read")
async def get_system_status(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取系统状态信息"""
    try:
        monitoring_service = MonitoringService(db)
        
        result = await monitoring_service.get_system_status()
        
        return ResponseDTO[Dict](
            success=True,
            message="获取系统状态成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取系统状态失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取系统状态失败"
        )


@router.get("/system/performance", response_model=ResponseDTO[Dict], summary="获取性能监控数据")
@PermissionDecorator.require_permission("system.monitoring", "read")
async def get_performance_metrics(
    time_range: int = Query(24, ge=1, le=168, description="时间范围(小时)"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取性能监控数据"""
    try:
        monitoring_service = MonitoringService(db)
        
        result = await monitoring_service.get_performance_metrics(time_range)
        
        return ResponseDTO[Dict](
            success=True,
            message="获取性能数据成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取性能数据失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取性能数据失败"
        )


@router.get("/system/realtime", response_model=ResponseDTO[Dict], summary="获取实时监控数据")
@PermissionDecorator.require_permission("system.monitoring", "read")
async def get_real_time_data(
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取实时系统数据"""
    try:
        monitoring_service = MonitoringService(db)
        
        result = await monitoring_service.get_real_time_data()
        
        return ResponseDTO[Dict](
            success=True,
            message="获取实时数据成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取实时数据失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取实时数据失败"
        )


# ==================== 日志管理API ====================

@router.get("/logs/query", response_model=ResponseDTO[Dict], summary="查询日志")
@PermissionDecorator.require_permission("system.logs", "read")
async def query_logs(
    log_type: Optional[str] = Query(None, description="日志类型"),
    level: Optional[str] = Query(None, description="日志级别"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    user_id: Optional[int] = Query(None, description="用户ID"),
    keyword: Optional[str] = Query(None, description="关键词"),
    ip_address: Optional[str] = Query(None, description="IP地址"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(50, ge=1, le=200, description="每页数量"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """查询日志记录"""
    try:
        log_service = LogService(db)
        
        result = await log_service.query_logs(
            log_type=log_type,
            level=level,
            start_time=start_time,
            end_time=end_time,
            user_id=user_id,
            keyword=keyword,
            ip_address=ip_address,
            page=page,
            size=size
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="查询日志成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"查询日志失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="查询日志失败"
        )


@router.post("/logs/analyze", response_model=ResponseDTO[Dict], summary="日志分析")
@PermissionDecorator.require_permission("system.logs", "analyze")
async def analyze_logs(
    request: LogAnalysisRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """日志分析统计"""
    try:
        log_service = LogService(db)
        
        result = await log_service.analyze_logs(
            analysis_type=request.analysis_type,
            time_range=request.time_range,
            group_by=request.group_by
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="日志分析完成",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"日志分析失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="日志分析失败"
        )


@router.post("/logs/export", response_model=ResponseDTO[Dict], summary="导出日志")
@PermissionDecorator.require_permission("system.logs", "export")
async def export_logs(
    request: LogExportRequest,
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """导出日志数据"""
    try:
        log_service = LogService(db)
        
        result = await log_service.export_logs(
            export_format=request.export_format,
            log_type=request.log_type,
            start_time=request.start_time,
            end_time=request.end_time,
            max_records=request.max_records
        )
        
        return ResponseDTO[Dict](
            success=True,
            message="日志导出完成",
            data=result
        )
        
    except (ValidationError, BusinessError) as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        logger.error(f"导出日志失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="导出日志失败"
        )


@router.get("/logs/statistics", response_model=ResponseDTO[Dict], summary="获取日志统计")
@PermissionDecorator.require_permission("system.logs", "read")
async def get_log_statistics(
    time_range: int = Query(24, ge=1, le=168, description="时间范围(小时)"),
    db: Session = Depends(get_db),
    current_user: Dict[str, Any] = Depends(get_current_active_user)
):
    """获取日志统计信息"""
    try:
        log_service = LogService(db)
        
        result = await log_service.get_log_statistics(time_range)
        
        return ResponseDTO[Dict](
            success=True,
            message="获取日志统计成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取日志统计失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取日志统计失败"
        )